var MapHelper = function () {
    var map = null;
    var config={
        center:[13723777.719260542, 4067677.1410778337],
        target: 'map',
        zoomSet:16,
        currentZoom:14,
        maxZoom:21,
        minZoom:1
    };
    var featuresOverlay = null,highlight = null,
        draw = null,
        drawLayerArr = [],
        featureOverlay, vectorLayer,deptVectorLayer,
        gridAreaLayer = new ol.layer.Vector({
            zIndex: 0
        }),
        pointLayer = new ol.layer.Vector({
            zIndex: 0
        });


    //初始化地图
    function initMap(_config) {
        config = $.extend(config, _config);
        if (map === null) {
            map = new ol.Map({
                layers: [
                    new ol.layer.Tile({
                source: new ol.source.XYZ({
                    //   url:'http://www.google.cn/maps/vt?lyrs=t@189&gl=cn&x={x}&y={y}&z={z}'
                    //    url: 'http://www.google.cn/maps/vt/pb=!1m4!1m3!1i{z}!2i{x}!3i{y}!2m3!1e0!2sm!3i380072576!3m8!2szh-CN!3scn!5e1105!12m4!1e68!2m2!1sset!2sRoadmap!4e0!5m1!1e0'
                    //     url:'http://mt0.google.cn/maps/vt?lyrs=s@773&gl=cn&x={x}&y={y}&z={z}'
                    //  url:'http://www.google.cn/maps/vt?lyrs=m@189&gl=cn&x={x}&y={y}&z={z}'
                    //         url:'http://www.google.cn/maps/vt?lyrs=s@189&gl=cn&x={x}&y={y}&z={z}'
                   //url:'http://www.google.cn/maps/vt?lyrs=h@189&gl=cn&x={x}&y={y}&z={z}'
                	   // url:'http://192.168.0.100/mapServer1/{z}/{x}/{y}.jpg'
                	//可以自行下载地图瓦片进行内网部署
                   url:'http://mt2.google.cn/vt/lyrs=s&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}'
                }) 
            })
                ],
                target: config.target,
                view: new ol.View({
                    center: config.center,
                    zoom: config.currentZoom,
                    maxZoom: config.maxZoom,
                    minZoom: config.minZoom
                })
            }); 
        }
        map.on('click', function (evt) {
            var _spotIdArr = [];
            map.forEachFeatureAtPixel(evt.pixel, function (feature) {
                if(feature.getProperties().type === "spot" && $.inArray(feature.getProperties()["id"],_spotIdArr) === -1){
                    _spotIdArr.push(feature.getProperties()["id"]);
                }
            });
            if(_spotIdArr.length !== 0){
                window.tableReload(_spotIdArr);
            }
        });


    }
    //清除图层
    function clear() {
        if (gridAreaLayer !== null) {
            if (gridAreaLayer.getSource() !== null) {
                gridAreaLayer.getSource().clear(true);
            }
            map.removeLayer(gridAreaLayer);
        }
        //清除绘画图层
        if (drawLayerArr != null) {
            for (var i = 0; i < drawLayerArr.length; i++) {
                map.removeLayer(drawLayerArr[i]);
                drawLayerArr[i] = null;
            }
        }
        if (draw != null) {
            map.removeInteraction(draw);
        }

        removeHostArea();
    }

    //判断地图是否含有图层
    function isHaveLayer(layer) {
        var st = false;
        var layers = map.getLayers(); //debugger;
        for (var i = 0; i < layers.getArray().length; i++) {
            if (layers.getArray()[i] == layer) {
                st = true;
                break;
            }
        }
        return st;
    }

    function initHotAreaSet(){
        map.on("moveend", initFourCornersHotArea)
        map.getView().on("change:resolution", initFourCornersHotArea);
    }
    /**
     * 初始化四角热区
     * @param options
     */
    function initFourCornersHotArea() {
        if (map.getView().getZoom() > config.zoomSet ) {
            var geojsonObject = {
                "type": "FeatureCollection",
                "features": []
            };
            //根据地图可视范围大小计算地图四个顶点坐标
            var bbox = map.getView().calculateExtent(map.getSize());
            //查询可视范围内标注的坐标
            $.ajax({
                url:  '/map/camera/hotArea/fourCorners/',
                method: 'GET',
                data: {
                    minX: bbox[0], minY: bbox[1], maxX: bbox[2], maxY: bbox[3]
                },
                success: function (response) {
                	console.log(response);
                    if (response.code == 200) {
                    	//一、当地图要加载的是区域范围的时候
                    	//构建数据为地图展示需要的形式
                        $.each(response.data, function (index, dda) {
                            var val = response.data[index];
                            //WKT(Well-known text)是开放地理空间联盟OGC（Open GIS Consortium ）制定的一种文本标记语言
                            var geometry = new ol.format.GeoJSON().writeGeometryObject(new ol.format.WKT().readGeometry(val.buildCroodsGeometry));
                            //下面也是规定的数据格式
                            var features = {
                                type: "Feature",
                                id: val.id,
                                properties: {type: 'spot', id: val.id, name: val.buildName, address: val.buildAddress},
                                geometry: geometry
                            };
                            
                            geojsonObject.features.push(features);
                        });
                        //初始化或者清理矢量图层
                        if (vectorLayer == null) {
                            vectorLayer = new ol.layer.Vector({zIndex: 1});
                            vectorLayer.setStyle(createHasOwnSpotStyle());
                        } else {
                            vectorLayer.getSource().clear(true);
                            map.removeLayer(vectorLayer);
                        }
                        //将返回组织好的数据加载到vectorLayer中
                        vectorLayer.setSource(new ol.source.Vector({
                            features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
                        }));
                        //设置每个点的名称
                        vectorLayer.getSource().forEachFeature(function(sfeat){
                            sfeat.setStyle(createHasOwnSpotStyle(sfeat.get('name')));
                        });
                        //将矢量图层加载到地图上面
                        map.addLayer(vectorLayer);
                    }
                },
                failure: function () {
                }
            });
            if (featuresOverlay == null) {
                //debugger;
                featuresOverlay = new ol.layer.Vector({
                    zIndex: 4, //数值越大越浮在上面
                    source: new ol.source.Vector()
                });
                map.addLayer(featuresOverlay);
            }//debugger;
            map.on('pointermove', hotAreaDisplayFeatureInfo);
        } else {
            layer.msg("未进入指定缩放级别");
            removeHostArea();
            map.un('pointermove', hotAreaDisplayFeatureInfo);
        }

    }

    //鼠标箭头移动到哪里哪里展示不一样的样式
    function hotAreaDisplayFeatureInfo(evt){
        if (evt.dragging) {
            return;
        }
        //获取当前鼠标像素点上面的地图特征信息
        var pixel = map.getEventPixel(evt.originalEvent);
        var feature = map.forEachFeatureAtPixel(pixel, function (feature, layer) {
            return feature;
        });
        //根据当前鼠标像素点的数据来判断是否为要特殊显示
        if (feature) {
            //debugger;  //解决鼠标在标记区域移动不显示楼房的问题
            if (feature.getProperties()["type"] == "GridArea" || feature.getProperties()["type"] == "gridarea") {
                return;
            }
        }
        //初始化后默认加载的热区样式
        if (featuresOverlay) {
        	//当前地图特征和高亮显示的特征是否相同
            if (feature !== highlight) {
                if (highlight) {
                	//不相同且有高亮显就将高亮显示设置为普通热区显示
                    highlight.setStyle(createHasOwnSpotStyle(highlight.get("name")));
                    //去除热区上的高亮显示
                    featuresOverlay.getSource().removeFeature(highlight);
                }
                if (feature) {
                    //debugger;
                	//清除覆盖物样式
                    featuresOverlay.getSource().clear(true);
                    //当前数据样式加载为热区样式
                    feature.setStyle(createOverLayStyle(feature.get("name")));
                    //加载到覆盖物上面
                    featuresOverlay.getSource().addFeature(feature);

                }
                //将当前属性标记为高亮显示
                highlight = feature;
            }
        }
    }




    function removeHostArea(){
        if (deptVectorLayer != null) {
            deptVectorLayer.getSource().clear(true);
            map.removeLayer(deptVectorLayer);
            deptVectorLayer = null;
        }
        if (vectorLayer != null) {
            vectorLayer.getSource().clear(true);
            map.removeLayer(vectorLayer);
            vectorLayer = null;
        }

        if (featuresOverlay != null) {
            featuresOverlay.getSource().clear(true);
            map.removeLayer(featureOverlay);
            featuresOverlay = null;
        }
        highlight = null;
        map.un('pointermove', hotAreaDisplayFeatureInfo);
        map.un("moveend", initFourCornersHotArea)
        map.getView().un("change:resolution", initFourCornersHotArea);
    }

    /**
     * 创建已有热区默认样式
     * @returns {ol.style.Style}
     */
    function createHasOwnSpotStyle(text) {
        return new ol.style.Style({
            fill: new ol.style.Fill({
                color: 'rgba(255,255,255,0.3)'
            }),
            stroke: new ol.style.Stroke({
                color: '#2ABDE2',
                width: 1
            }),
            text: new ol.style.Text({
                text:text||"",
                font: '12px Calibri,sans-serif',
                fill: new ol.style.Fill({
                    color: '#000'
                }),
                stroke: new ol.style.Stroke({
                    color: '#fff',
                    width: 1
                })
            })
        });
    }

    /**
     * 创建鼠标移动到热区样式
     * @returns {ol.style.Style}
     */
    function createOverLayStyle(text) {
        return new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: '#ffd800',
                width: 4
            }),
            fill: new ol.style.Fill({
                color: 'rgba(255,255,255,0.6)'
            }),
            text: new ol.style.Text({
                text:text||"",
                font: '12px Calibri,sans-serif',
                fill: new ol.style.Fill({
                    color: '#000'
                }),
                stroke: new ol.style.Stroke({
                    color: '#fff',
                    width: 3
                })
            })
        });
    }

    //地图转为编辑模式
    function ondraw(options) {
    	//在地图上创建feature数组
        var createFeatures = function (map) {
            var features = new ol.Collection();
            featuresOverlay = new ol.layer.Vector({
                source: new ol.source.Vector({
                    features: features
                }),
                style: new ol.style.Style({
                    fill: new ol.style.Fill({
                        color: 'rgba(255,255,255,0.2)'
                    }),
                    stroke: new ol.style.Stroke({
                        color: '#ffcc33',
                        width: 1
                    }),
                    image: new ol.style.Circle({
                        radius: 3,
                        fill: new ol.style.Fill({
                            color: '#ffcc33'
                        })
                    })
                })
            });
            map.addLayer(featuresOverlay);
            return features;
        };
        //点击操作切换到画图模式
        map.removeInteraction(draw);
        // 点，线，区域
        var type = options.type || "Point"; //Point\LineString\Polygon
        //draw方法修改
        //获取绘画属性
        var fillColor = options.fillColor || 'rgba(255,255,255,0.2)';
        var strokeColor = options.strokeColor || '#df3434';
        var strokeWidth = options.strokeWidth || 3;
        var features = options.features || new ol.Collection();
        
        var source = new ol.source.Vector({
            features: features
        });
        var drawLayer = new ol.layer.Vector({
            source: source,
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    color: fillColor
                }),
                stroke: new ol.style.Stroke({
                    color: strokeColor,
                    width: strokeWidth
                }),
                image: new ol.style.Circle({
                    radius: 5,
                    fill: new ol.style.Fill({
                        color: '#df3434'
                    })
                })
            })
        });
        map.addLayer(drawLayer);
        drawLayerArr.push(drawLayer);
        //画图工具
        draw = new ol.interaction.Draw({
            source: source,
            type: type
        })
        //callback中拿到的参数是个对象,有3个属性
        //1.The feature being drawn.  2.The event target.  3.The event type.
        //结束画图模式
        draw.on("drawend", function (x, y, z) {
            options.callback(x, y, z);
            //debugger;
            if (featuresOverlay !== null) {
                featuresOverlay.setSource(null);
                featuresOverlay.setMap(null);
                featuresOverlay = null;
            }
            if (draw != null) {
                map.removeInteraction(draw);
            }
        });
        //this.controls.draw = draw;
        map.addInteraction(draw);
    }

    var drawIcon = function (options) {
        options.layer = options.layer || gridAreaLayer;
        //画图标
        var iconStyle = function (options) {
            var options = options ? options : {};
            return new ol.style.Style({
                image: new ol.style.Icon({
                    anchor: options.anchor || undefined,
                    anchorXUnits: options.anchorXUnits || undefined,
                    anchorYUnits: options.anchorYUnits || undefined,
                    size: options.size || undefined,
                    imgSize: options.imgSize || undefined,
                    offset: options.offset || [0, 0],
                    scale: options.scale || undefined,
                    //src: options.icon || undefined,
                    src: options.icon || '/aladin/images/Marker-32.png',
                    img: options.img || undefined
                }),
                text: options.noText ? null :new ol.style.Text({
                    offsetX: options.offsetX || 28,
                    offsetY: options.offsetY || -36,
                    text: options.name || "",
                    font: '10px 宋体',
                    fill: new ol.style.Fill({
                        color: '#000'
                    }),
                    stroke: new ol.style.Stroke({
                        color: '#fff',
                        width: 2
                    })
                })
            });
        };
        var source;
        if (typeof (options.source) == "undefined") {
            source = new ol.source.Vector();
        } else {
            source = options.source;
        }
        var style;
        if (typeof (options.style) != 'undefined') {
            style = iconStyle(options.style);
        }
        $.each(options.properties, function ( index,d) {
            if (d.data.x != "" && d.data.x != null) {
                var feature = new ol.Feature({
                    'id': d.data.id,
                    code: d.data.code || "",
                    //'properties': { id: d.data.id, type: d.data.type, x: d.data.x, y: d.data.y },
                    'geometry': new ol.geom.Point([d.data.x, d.data.y]),
                    raw: d.data.raw,
                    type: d.data.type
                });
                if (typeof (d.style) != 'undefined') {
                    style = iconStyle(d.style);
                }
                //style.getText().setText(d.data.name);
                //console.log(d)
                feature.setStyle(style);
                source.addFeature(feature);

            }
        });
        options.layer.setSource(source);
        var st = isHaveLayer(options.layer);
        //map.removeLayer(options.layer);
        if(!st) {
            map.addLayer(options.layer);
        }
    };
    
    //停止画图
    function undraw() {
        if (map.getControls().draw) {
            try {
                map.getControls().draw.setActive(false);
            } catch (ex) {}
        }
    }

  //开始画图
    var newOndraw = function (options) {

        var createFeatures = function (map) {
            var features = new ol.Collection();
            featuresOverlay = new ol.layer.Vector({
                source: new ol.source.Vector({ features: features }),
                style: new ol.style.Style({
                    fill: new ol.style.Fill({
                        color: 'rgba(255,255,255,0.2)'
                    }),
                    stroke: new ol.style.Stroke({
                        color: '#ffcc33',
                        width: 1
                    }),
                    image: new ol.style.Circle({
                        radius: 3,
                        fill: new ol.style.Fill({
                            color: '#ffcc33'
                        })
                    })
                })
            });
            map.addLayer(featuresOverlay);
            return features;
        };
        //点击操作切换到画图模式 
        map.removeInteraction(draw);
        clickOperation = 'draw';
        //var features = options.features || createFeatures(map);
        //console.log(features)
        var type = options.type || "Point";//Point\LineString\Polygon
        //draw = new ol.interaction.Draw({
        //    features: features,
        //    type: type
        //});
        //draw方法修改
        //获取绘画属性
        var fillColor = options.fillColor || 'rgba(255,255,255,0.2)';
        var strokeColor = options.strokeColor || '#df3434';
        var strokeWidth = options.strokeWidth || 3;
        var features = options.features || new ol.Collection();
        //console.log(features)
        var source = new ol.source.Vector({
            features:features
        });
        var drawLayer = new ol.layer.Vector({
            source: source,
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    color: fillColor
                }),
                stroke: new ol.style.Stroke({
                    color: strokeColor,
                    width: strokeWidth
                }),
                image: new ol.style.Circle({
                    radius: 5,
                    fill: new ol.style.Fill({
                        color: '#df3434'
                    })
                })
            })
        });
        map.addLayer(drawLayer);
        drawLayerArr.push(drawLayer);
        draw = new ol.interaction.Draw({
            source: source,
            type: type,
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    color: fillColor
                }),
                stroke: new ol.style.Stroke({
                    color: strokeColor,
                    width: strokeWidth
                }),
                image: new ol.style.Circle({
                    radius: 5,
                    fill: new ol.style.Fill({
                        color: '#ffcc33'
                    })
                })
            })
        })
        //callback中拿到的参数是个对象,有3个属性
        //1.The feature being drawn.  2.The event target.  3.The event type.
        draw.on("drawend", options.callback); 
        map.addInteraction(draw);
    };
    //停止画图
    var newUndraw = function () {
         
        clickOperation = 'hotArea';//点击操作回到默认
    };
    
    return {
        initMap: function (_config) {
            initMap(_config);
        },
        clear: function () {
            clear();
        },
        ondraw: function (options) {
            ondraw(options);
        },
        drawIcon: function (options) {
        	drawIcon(options);
        }, 
        initHotArea: function () {
            initHotAreaSet();
            initFourCornersHotArea();
        },
        removeHostArea:function(){
            removeHostArea();
        },
        newOndraw : function(options){
            return newOndraw(options);
        },
        newUndraw : function(){
            return newUndraw();
        },
    }
}();